<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 10/11/24
 * Time: 6:20 PM
 */

namespace app\common\command;

use app\common\model\skits\Skits;
use app\common\model\skits\SkitsEpisodes;
use app\common\service\douyin\DouyinService;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;


class SyncDouyinEpisodes extends Command
{
    protected function configure()
    {
        $this->setName('sync_douyin_episodes')
            ->addOption('v', null, Option::VALUE_OPTIONAL, '拉取版本')
            ->setDescription('同步抖音剧集');
    }


    /**
     * 同步抖音剧集
     *
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        $skits = Skits::where('douyin_status', 3)->select();
        if ($skits->isEmpty()) {

            return;
        }
        $output->writeln('开始同步抖音短剧集，共计：' . $skits->count() . '条');

        foreach ($skits as $item) {
            if (!$episodesCount = $item->episodes_count ?? 0) {
                continue;
            }
            // 获取同步版本
            $v         = $input->hasOption('v') ? (int)$input->getOption('v') : ($item->douyin_version ?? 1);
            $totalPage = intval(ceil($episodesCount / 50));
            for ($page = 1; $page <= $totalPage; $page++) {
                $offset       = ($page - 1) * 50;
                $episodesList = DouyinService::fetchAlbum($item->douyin_app_id, $item->douyin_drama_id, $v, $offset);
                foreach ($episodesList as $episodesItem) {
                    $episodes = SkitsEpisodes::where('douyin_media_id', $episodesItem['open_video_id'])->findOrEmpty();
                    if ($episodes->isEmpty()) {
                        continue;
                    }
                    $episodes->douyin_episodes_id = $episodesItem['episode_id'] ?? '';
                    $episodes->episodes_order     = $episodesItem['seq'] ?? 1;
                    $episodes->save();
                }
                if (count($episodesList) < 50) {
                    continue;
                }
            }
        }

    }

}
